// // ******************************************************************
// //       /\ /|       @file       TempFileCleanupService.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-03-01 11:03
// //    *(__\_\        @Copyright  Copyright (c) , 2025-03-01 11:03 Await
// // ******************************************************************

namespace AutomaticSubtitles.Service.Infrastructure.Services;

/// <summary>
/// 临时文件清理服务
/// </summary>
public class TempFileCleanupService : BackgroundService
{
    private readonly SubtitleExtractionConfig _config;
    private readonly ILogger<TempFileCleanupService> _logger;
    private readonly IServiceProvider _serviceProvider;
    private Timer _timer;

    public TempFileCleanupService(
        ILogger<TempFileCleanupService> logger,
        IServiceProvider serviceProvider,
        SubtitleExtractionConfig config)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _config = config;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        if (!_config.EnableAutoCleanup)
        {
            _logger.LogInformation("自动清理临时文件功能已禁用");
            return Task.CompletedTask;
        }

        _logger.LogInformation($"临时文件清理服务已启动，清理间隔：{_config.AutoCleanupIntervalHours}小时");

        // 创建定时器，定期清理临时文件
        _timer = new Timer(CleanupTempFiles, null, TimeSpan.Zero, TimeSpan.FromHours(_config.AutoCleanupIntervalHours));

        return Task.CompletedTask;
    }

    private async void CleanupTempFiles(object state)
    {
        try
        {
            _logger.LogInformation("开始清理临时文件...");

            // 确定媒体库大小和临时文件保留期
            var retentionHours = _config.TempFileRetentionHours;
            var isLargeLibrary = false;

            using (var scope = _serviceProvider.CreateScope())
            {
                var mediaRepository = scope.ServiceProvider.GetRequiredService<IRepository<DataAccess.Model.Auto_Media>>();
                var mediaCount = await mediaRepository.GetCountAsync();

                _logger.LogInformation($"当前媒体库大小：{mediaCount} 个媒体文件");

                if (mediaCount >= _config.LargeLibraryThreshold)
                {
                    isLargeLibrary = true;
                    retentionHours = _config.LargeLibraryTempFileRetentionHours;
                    _logger.LogInformation($"检测到大型媒体库，使用较短的临时文件保留期：{retentionHours}小时");
                }
                else
                {
                    _logger.LogInformation($"使用标准临时文件保留期：{retentionHours}小时");
                }
            }

            // 执行清理
            var deletedCount = AudioSubtitleHelper.CleanupTempFiles(retentionHours, _config.CleanFinalDirectory);

            _logger.LogInformation($"临时文件清理完成，共删除 {deletedCount} 个文件");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清理临时文件时发生错误");
        }
    }

    public override Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("临时文件清理服务已停止");

        _timer?.Change(Timeout.Infinite, 0);

        return base.StopAsync(cancellationToken);
    }

    public override void Dispose()
    {
        _timer?.Dispose();
        base.Dispose();
    }
}